﻿

// Event handler for the Office.initialize event
// to make sure the runtime environment is ready.
var senderEmail = "";
var map;
Office.initialize = function () {
    "use strict";
    // Both runtime environment and
    // DOM are ready, start mail app code.

    // Checks for the DOM to load.
    $(document).ready(function () {

        map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), {
            credentials: "AiiTj4DpnmuPCqpitM3Bv34aQCUD1EQUxVc1oLTKPDezlvPQBHwApPAPNhVi9Yjx"
        });
       
        senderEmail = Office.context.mailbox.item.sender.emailAddress;
        
    var restUrl = "/_api/lists/getbytitle('Contragents')/items?" +
               "$select=Address&$filter=startswith(EMail,'" + encodeURIComponent(senderEmail) + "')";

    $.ajax({
        url: restUrl,
        dataType: "json",        
        success: function (result) {                      
            //  $("td#sender").html(result.d.results[0].Address);
            shopwLocationbyAddress(result.d.results[0].Address);
        },
        beforeSend: function (xhrObj) {
            xhrObj.setRequestHeader("Accept", "application/json; odata=verbose");            
        }
    });


    });
}

function shopwLocationbyAddress(address){
  
    var searchRequest = 'https://dev.virtualearth.net/REST/v1/Locations/'
        + address
        + ',RU?output=json&jsonp=GeocodeCallback&c=ru&key=AiiTj4DpnmuPCqpitM3Bv34aQCUD1EQUxVc1oLTKPDezlvPQBHwApPAPNhVi9Yjx';

    $.getScript(searchRequest);
  
}

function GeocodeCallback(result) {
    if (result &&
                   result.resourceSets &&
                   result.resourceSets.length > 0 &&
                   result.resourceSets[0].resources &&
                   result.resourceSets[0].resources.length > 0) {
        // Set the map view using the returned bounding box
        var bbox = result.resourceSets[0].resources[0].bbox;
        var viewBoundaries = Microsoft.Maps.LocationRect.fromLocations(new Microsoft.Maps.Location(bbox[0], bbox[1]), new Microsoft.Maps.Location(bbox[2], bbox[3]));
        map.setView({ bounds: viewBoundaries });

        // Add a pushpin at the found location
        var location = new Microsoft.Maps.Location(result.resourceSets[0].resources[0].point.coordinates[0], result.resourceSets[0].resources[0].point.coordinates[1]);
        var pushpin = new Microsoft.Maps.Pushpin(location);
        map.entities.push(pushpin);
    }

}






